
import 'dart:async';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:hbtrans_flutter/apis.dart';
import 'package:hbtrans_flutter/beans/LoginNewBean.dart';
import 'package:hbtrans_flutter/beans/login_bean.dart';
import 'package:hbtrans_flutter/const.dart';
import 'package:hbtrans_flutter/routes.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';
import 'package:hbtrans_flutter/utils/utils.dart';
import 'package:hbtrans_flutter/view/loading.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Register extends StatefulWidget {
  @override
  _RegisterState createState() => _RegisterState();
}

class _RegisterState extends State<Register> {
  Map<String, dynamic> data = Map();
  Map<String, dynamic> loginData = Map();
  //定义变量
  Timer _timer;
  //倒计时数值
  var countdownTime = 0;
  var editPhone='';
  var _scaffoldkey = new GlobalKey<ScaffoldState>();
  String mobile = '';
  LoadingDialog loadingDialog;

  //倒计时方法
  startCountdown() {
    countdownTime = 60;
    final call = (timer) {
      setState(() {
        if (countdownTime < 1) {
          _timer.cancel();
        } else {
          countdownTime -= 1;
        }
      });
    };
    _timer = Timer.periodic(Duration(seconds: 1), call);
  }

  void smsValidateCode() {
    MyDio.getInstance().clearInstance();
    MyDio.getInstance(url: Const.TRANS_SERVER_PATH_NEW3).post(Apis.sendNote, (data) async {
      print(data);
        Utils.getInstance().showSnackBar(_scaffoldkey,'验证码发送成功');
//        成功
        startCountdown();
    },params: data);
  }

  _handleCodeText() {
    return Text(countdownTime>0 ? '${countdownTime}s后重新获取' : '免费获取验证码',
      style: TextStyle(fontSize: 12,color: countdownTime>0 ? Color(0xff23AFDC) : Color(0xff23AFDC)),);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkToken();
  }

  void checkToken() async{
    SharedPreferences getSp=await SharedPreferences.getInstance();
    var token=getSp.getString("token");
    if(token.isNotEmpty){
      String route = '${Routes.mainPage}';
      Routes.router.navigateTo(context, route,
          replace: true, transition: TransitionType.fadeIn);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    MyDio.getInstance().clearInstance();
    if (_timer != null) {
      _timer.cancel();
    }
  }

  _showDialog() {
    loadingDialog = LoadingDialog(
      text: '请稍候...',
    );
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return loadingDialog;
        });
  }

  _setToken(String data) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var token = await prefs.setString('token',data);
  }

  _setId(String data) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var id = await prefs.setString('id',data);
  }
  _setPhone(String data) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var phone = await prefs.setString('phone',data);
  }

  _login() async {
    _showDialog();
    MyDio.getInstance(url: Const.TRANS_SERVER_PATH_NEW3).post(Apis.login,
            (data) {
          print(data);
          if (loadingDialog != null) {
            loadingDialog = null;
            Navigator.pop(context);
          }

//          LoginBean loginBean = LoginBean.fromJson(data);
//          _setToken(loginBean.token);
//          _setPhone(loginBean.user.phone);
           LoginNewBean loginNewBean=LoginNewBean.fromJson(data);
              _setToken(loginNewBean.token);
              _setId(loginNewBean.data.id);
              _setPhone(editPhone);
              print(loginNewBean.data.idcard);
            if(loginNewBean.data.idcard==null){
              String route = '${Routes.improve}';
              Routes.router.navigateTo(context, route,
                  replace: true, transition: TransitionType.fadeIn);
            }else{
              String route = '${Routes.mainPage}';
              Routes.router.navigateTo(context, route,
              replace: true, transition: TransitionType.fadeIn);
              }


        }, params: loginData);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      key: _scaffoldkey,
      body: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(30, 42, 40, 0),
            child: Column(
              children: <Widget>[
                SizedBox(height: 42,),
                Image.asset('images/icon_launcher.png',height:90 ,width: 90,fit: BoxFit.fill,),
                SizedBox(height: 42,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding:
                      const EdgeInsets.symmetric(vertical: 8, horizontal: 15),
                      child: ImageIcon(
                        AssetImage('images/icon_phone.png'),
                        size: 24,
                        color: Color(0xff23AFDC),
                      ),
                    ),
                    Expanded(
                      child: TextFormField(
                        onChanged: (value){
                          data['phone']=value;
                          loginData['phone']=value;
                          editPhone=value;
                        },
                          style: TextStyle(fontSize: 16, color: Colors.grey),
                          decoration: InputDecoration(
                            hintText: '请输入用户名',
                            hintStyle:
                            TextStyle(color: Color(0xff999999), fontSize: 16),),
                          autofocus: false,
                        ),
                    ),
                  ],
                ),
                SizedBox(height: 12,),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding:
                      const EdgeInsets.symmetric(vertical: 8, horizontal: 15),
                      child: ImageIcon(
                        AssetImage('images/ic_yzm.png'),
                        size: 26,
                        color: Color(0xff23AFDC),
                      ),
                    ),
                    Expanded(child: Stack(
                      alignment:Alignment.centerRight,
                      children: <Widget>[
                        TextFormField(
                          style: TextStyle(fontSize: 16, color: Colors.grey),
                          onChanged: (value){
                            loginData['code']=value;
                          },
                          decoration: InputDecoration(
                            hintText: '请输入验证码',
                            hintStyle:
                            TextStyle(color: Color(0xff999999), fontSize: 16),),
                          autofocus: false,
                        ),
                        GestureDetector(
                          onTap: (){
                            if (data['phone'] == null) {
                              Utils.getInstance().showSnackBar(_scaffoldkey,'用户名不能为空');
                              return;
                            }else{
                              if(countdownTime==0){
                                smsValidateCode();
                              }
                            }
                          },
//
                          child: Container(
                            alignment: Alignment.center,
                            width: 104,
                            height: 28,
                            decoration: BoxDecoration(
                              border: new Border.all(width: 1.0, color: Color(0xff23AFDC)),
                              borderRadius: new BorderRadius.all(new Radius.circular(4.0)),
                            ),
                            child: _handleCodeText(),
                          ),
                        ),
                      ],
                    ),),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 93,),
          MaterialButton(
            height: 45,
            minWidth: 325,
            elevation: 0,
            onPressed: () {
              if (loginData['phone'] == null) {
                Utils.getInstance().showSnackBar(_scaffoldkey,'用户名不能为空');
                return;
              }
              if (loginData['code'] == null) {
                Utils.getInstance().showSnackBar(_scaffoldkey,'验证码不能为空');
                return;
              }
              _login();
            },
            child: Text(
              "立即登录",
              style: TextStyle(color: Colors.white, fontSize: 18),
            ),
            color: Color(0xff23AFDC),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(40))),
          ),
        ],
      ),
    );
  }

}